package com.org.utils.encrypt;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import com.org.utils.string.StringUtils;

public class MD5Utils
{

	/**
	 * 用md5编码后的码值
	 * 
	 * @param sInput明码
	 * @return md5加密后的密码
	 */
	private static String getMD5Value(String sInput)
	{
		String algorithm = "";
		if (sInput == null)
		{
			return "null";
		}
		try
		{
			algorithm = System.getProperty("MD5.algorithm", "MD5");
		} catch (SecurityException se)
		{

		}

		MessageDigest md = null;
		try
		{
			md = MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}
		byte buffer[] = sInput.getBytes();
		for (int count = 0; count < sInput.length(); count++)
		{
			md.update(buffer, 0, count);
		}
		byte bDigest[] = md.digest();
		BigInteger bi = new BigInteger(bDigest);
		return (bi.toString(16));
	}

	/**
	 * 加密算法MD5
	 * 
	 * @param text
	 *            明文
	 * @return String 密文
	 */
	private final static String encoding(String text)
	{
		char hexDigits[] =
		{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		String encodingStr = null;
		try
		{
			byte[] strTemp = text.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++)
			{
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			encodingStr = new String(str);
		} catch (Exception e)
		{
		}
		return encodingStr;
	}

	private final static String[] hexDigits =
	{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	/**
	 * 对字符串进行MD5加密
	 * 
	 * @author E.FLY
	 * @date 2012-10-9
	 * @time 上午09:41:54
	 * @param inputString
	 *            要加密的字符串
	 * @return 返回加密后的字符串
	 */
	public static String generatePassword(String inputString)
	{
		return encryptByMD5(inputString);
	}

	/**
	 * 登录验证
	 * 
	 * @author E.FLY
	 * @date 2012-4-16
	 * @time 上午10:06:55
	 * @param md5Password
	 *            加密后的密码
	 * @param Password
	 *            未加密的密码
	 * @return
	 */
	public static boolean validatePassword(String md5Password, String Password)
	{
		if (md5Password.equals(encryptByMD5(Password)))
		{
			return true;
		} else
		{
			return false;
		}
	}

	public String getEncrypt(String originString)
	{
		return encryptByMD5(originString);
	}

	/**
	 * 对字符串进行MD5加密
	 * 
	 * @author E.FLY
	 * @date 2012-10-9
	 * @time 上午09:40:24
	 * @param originString
	 *            要加密的字符串
	 * @return 返回加密后的字符串
	 */
	public static String encryptByMD5(String originString)
	{
		if (originString != null)
		{
			try
			{
				MessageDigest md = MessageDigest.getInstance("MD5");
				// 使用指定的字节数组对摘要进行最后更新，然后完成摘要计算
				byte[] results = md.digest(originString.getBytes());
				// 将得到的字节数组变成字符串返回
				String resultString = byteArrayToHexString(results);
				String pass = resultString.toUpperCase();
				return pass;
			} catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
		return null;
	}

	public static String byteArrayToHexString(byte[] b)
	{
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++)
		{
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	/** 将一个字节转化成十六进制形式的字符串 */
	private static String byteToHexString(byte b)
	{
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	/**
	 * 随机生成字符串
	 * @author E.FLY
	 * @date 2012-7-27
	 * @time 下午06:30:51
	 * @param base
	 *            从该字符串中随机拿去 length个字符
	 * @param length
	 *            取出字符串个数
	 * @return
	 */
	public static String createRandom(String base, int length)
	{
		// randomCode用于保存随机产生的值。
		StringBuffer randomCode = new StringBuffer();
		// 创建一个随机数生成器类。
		Random random = new Random();
		// 设置默认生成4个验证码
		if (length == 0)
			length = 4;
		// 设置备选验证码:包括"a-z"和数字"0-9"
		if (StringUtils.isEmptyOrNull(base))
			base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

		int size = base.length();

		// 随机产生4位数字的验证码。
		for (int i = 0; i < length; i++)
		{
			// 得到随机产生的验证码数字。
			int start = random.nextInt(size);
			String strRand = base.substring(start, start + 1);
			// 将产生的四个随机数组合在一起。
			randomCode.append(strRand);
		}

		return randomCode.toString();
	}

	public static void main(String[] args)
	{
		System.out.println(getMD5Value("zhuzhu"));
		System.out.println(encoding("zhuzhu"));
		String pwd1 = "123456";
		String pwd2 = "";
		System.out.println("未加密的密码:" + pwd1);
		// 将123加密
		pwd2 = generatePassword(pwd1);
		System.out.println("加密后的密码:" + pwd2);

		System.out.print("验证密码是否下确:");
		if (validatePassword(pwd2, pwd1))
		{
			System.out.println("正确");
		} else
		{
			System.out.println("错误");
		}

		System.out.println(createRandom(null, 0) + "==========================");
	}
}
